<template>
  <div style="padding: 20px;">
    <div class="topLocation">训练安排管理 / 训练安排</div>
    <div class="topTool">
      <div class="group">球员姓名：</div>
      <el-input v-model="searchPlayerName" placeholder="请输入球员姓名" style="margin-right: 50px;"></el-input>
      <div class="group">教练姓名：</div>
      <el-input v-model="searchCoachName" placeholder="请输入教练姓名" style="margin-right: 50px;"></el-input>
      <div class="group">训练地点：</div>
      <el-input v-model="searchTrainingLocation" placeholder="请输入训练地点" style="margin-right: 50px;"></el-input>
      <div class="group">训练状态：</div>
      <el-select v-model="searchStatus" placeholder="请选择训练状态">
        <el-option label="未完成" value="未完成"></el-option>
        <el-option label="已完成" value="已完成"></el-option>
        <el-option label="所有训练状态" value=""></el-option>
      </el-select>
      <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
      <el-button type="primary" :icon="Plus" @click="handleAdd">添加</el-button>
      <el-button type="danger" :icon="Delete" @click="handleDelList" v-if="multipleSelection.length > 0">删除自己发布的训练</el-button>
    </div>
    <el-table
        :data="trainingData"
        :header-cell-style="{ background: '#f6f9fa'}"
        @sort-change="handleSortChange"
        empty-text="暂无数据"
        @selection-change="handleSelectionChange">
      <el-table-column type="selection"/>
      <el-table-column prop="id" label="ID"  sortable></el-table-column>
      <el-table-column prop="playerName" label="球员姓名" ></el-table-column>
      <el-table-column prop="coachName" label="教练姓名" ></el-table-column>
      <el-table-column prop="trainingDate" label="训练日期"  :formatter="formatDate"></el-table-column>
      <el-table-column prop="trainingTime" label="训练时间" ></el-table-column>
      <el-table-column prop="trainingLocation" label="训练地点" ></el-table-column>
      <el-table-column prop="trainingContent" label="训练内容" ></el-table-column>
      <el-table-column prop="status" label="训练状态" ></el-table-column>
      <el-table-column label="操作" width="240">
        <template #default="{ row }">
          <el-button type="primary" :icon="Edit" size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" :icon="Delete" size="small" @click="handleDelete(row)">删除</el-button>
          <el-button type="success" :icon="Check" size="small" @click="handleComplete(row)">完成</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
        background
        v-model:currentPage="currentPage"
        v-model:pageSize="pageSize"
        :page-sizes="[5, 10, 20]"
        :total="total"
        layout="prev, pager, next, sizes"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />

    <!-- 训练信息弹窗 -->
    <el-dialog v-model="dialogFormVisible" :title="dialogTitle">
      <el-form :model="form" label-width="100px">
        <el-form-item label="球员姓名">
          <el-input v-model="form.playerName" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="训练日期">
          <el-date-picker
              v-model="form.trainingDate"
              type="date"
              placeholder="选择日期"
              style="width: 100%;"
              :picker-options="{ firstDayOfWeek: 1 }"
          />
        </el-form-item>
        <el-form-item label="训练时间">
          <el-input v-model="form.trainingTime" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="训练地点">
          <el-input v-model="form.trainingLocation" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="训练内容">
          <el-input v-model="form.trainingContent" autocomplete="off"/>
        </el-form-item>
      </el-form>

      <!-- 弹窗底部按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="dialogOk">确定</el-button>
          <el-button @click="dialogFormVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import axios from 'axios';
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox, ElMessageBoxOptions } from 'element-plus';
import {Check, Delete, Edit, Plus, Search} from "@element-plus/icons-vue";
import {useRoute} from "vue-router";

// 响应式变量
const trainingData = ref([]);
const currentPage = ref(1);
const pageSize = ref(5);
const total = ref(0);
const searchPlayerName = ref('');
const searchCoachName = ref('');
const searchTrainingLocation = ref('');
const searchStatus = ref('');

// 通过 useRoute 获取路由参数
const route = useRoute();
const name = ref(route.query.name ? String(route.query.name) : '');
const role = ref(route.query.role ? String(route.query.role) : '');

// 日期格式化函数
const formatDate = (row, column, cellValue) => {
  if (!cellValue) return '无日期';
  const date = new Date(cellValue);
  if (isNaN(date.getTime())) {
    return '无效日期';
  }
  return date.toLocaleDateString();
};

// 组件挂载时加载数据
onMounted(() => {
  getData();
});

// 获取数据
const getData = () => {
  axios.get('http://localhost:8080/trainingschedule/page', {
    params: {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      playerName: searchPlayerName.value,
      coachName: searchCoachName.value,
      trainingLocation: searchTrainingLocation.value,
      status: searchStatus.value
    }
  }).then(response => {
    trainingData.value = response.data.records;
    total.value = response.data.total;
  }).catch(error => {
    console.error(error);
  });
};

const handleCurrentChange = (pageNum) => {
  currentPage.value = pageNum;
  getData();
};

const handleSizeChange = (size) => {
  pageSize.value = size;
  getData();
};

// 删除操作
const handleDelete = (row) => {
  if (row.coachName !== name.value) {
    ElMessage.warning('您没有权限删除该训练安排！');
    return;
  }

  ElMessageBox.confirm(
      '您确定要删除球员姓名为【' + row.playerName + '】的训练安排吗?',
      '危险操作',
  ).then(() => {
    delrow(row.id);
    ElMessage({
      type: 'success',
      message: '完成删除！',
    });
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消删除!',
    });
  });
};

// 删除请求
const delrow = (id) => {
  axios.delete(`http://localhost:8080/trainingschedule/delete/${id}`)
      .then(response => {
        getData();
      })
      .catch(error => {
        console.error(error);
      });
};

// 查询
const handleSearch = () => {
  const params = {
    playerName: searchPlayerName.value || null,
    coachName: searchCoachName.value || null,
    trainingLocation: searchTrainingLocation.value || null,
    status: searchStatus.value || null
  };
  axios.get('http://localhost:8080/trainingschedule/search', { params })
      .then(response => {
        trainingData.value = response.data;
        total.value = response.data.length; // 假设返回的是数组，直接使用数组的长度作为总数
      })
      .catch(error => {
        console.error(error);
        ElMessage.error('查询失败');
      });
};

// 字段排序
const handleSortChange = (sortData) => {
  const { prop, order } = sortData;
  trainingData.value = trainingData.value.sort((a, b) => {
    if (order === 'ascending') {
      return a[prop] > b[prop] ? 1 : -1;
    } else {
      return a[prop] < b[prop] ? 1 : -1;
    }
  });
};

// 创建响应式变量multipleSelection，用于存储当前选中的数据行
let multipleSelection = ref([]);

// 处理表格行选中状态变化的方法，val是当前选中的数据行数组
const handleSelectionChange = (val) => {
  // 清空数组，确保每次更新都是最新选中状态
  multipleSelection.value = [];
  val.forEach(item => {
    // 只存储 coachName 与 name 匹配的数据的 id
    if (item.coachName === name.value) {
      multipleSelection.value.push(item.id);
    }
  });
};

// 批量删除
const handleDelList = () => {
  ElMessageBox.confirm(
      '您确定要删除选择的训练安排吗?',
      '危险操作',
  ).then(() => {
    // 获取符合条件的 ids
    const ids = multipleSelection.value;
    axios.delete(`http://localhost:8080/trainingschedule/delete/batch`, { data: ids })
        .then(response => {
          getData();
          ElMessage({ type: 'success', message: '完成批量删除！' });
        })
        .catch(error => {
          console.error(error);
          ElMessage({ type: 'error', message: '删除失败！' });
        });
  }).catch(() => {
    ElMessage({ type: 'info', message: '取消删除!' });
  });
};

// 弹窗相关变量
const dialogFormVisible = ref(false); // 控制弹窗显示
const form = ref({
  id: '',
  playerName: '',
  coachName: '',
  trainingDate: '',
  trainingTime: '',
  trainingLocation: '',
  trainingContent: '',
  status: '未完成', // 默认不设置初始值
}); // 表单数据
const dialogType = ref('add'); // 初始化弹出框的类型为增加弹窗

// 处理添加按钮点击事件
const handleAdd = () => {
  dialogFormVisible.value = true;
  dialogType.value = 'add';
  // 设置表单默认值
  form.value = {
    id: '',
    playerName: '',
    coachName: name.value,
    trainingDate: '',
    trainingTime: '',
    trainingLocation: '',
    trainingContent: '',
    status: '未完成', // 默认为未完成
  };
};

// 设置弹窗的标题
const dialogTitle = computed(() => {
  return dialogType.value === 'add' ? '新增训练安排' : '编辑训练安排';
});

// 确定按钮点击事件
const dialogOk = () => {
  dialogFormVisible.value = false;
  if (dialogType.value === 'add') {
    addTrainingSchedule();
  } else {
    updateTrainingSchedule();
  }
};

// 添加训练安排
const addTrainingSchedule = () => {
  const newTrainingSchedule = { ...form.value };
  axios.post('http://localhost:8080/trainingschedule/add', newTrainingSchedule)
      .then(response => {
        ElMessage.success('添加训练安排成功');
        getData(); // 在添加数据后调用获取数据的方法
      })
      .catch(error => {
        ElMessage.error('添加训练安排失败');
        console.error(error);
      });
};

// 处理编辑按钮点击事件
const handleEdit = (row) => {
  // 判断训练安排是否已完成，如果已完成则不允许编辑
  if (row.status === '已完成') {
    ElMessage.warning('已完成的训练安排不能编辑');
    return;
  }

  // 判断是否为自己创建的训练安排，如果不是则不允许编辑
  if (row.coachName !== name.value) {
    ElMessage.warning('只能编辑自己创建的训练安排');
    return;
  }

  // 允许编辑，设置表单数据并打开编辑弹窗
  form.value = { ...row };
  dialogType.value = 'edit';
  dialogFormVisible.value = true;
};

// 更新训练安排
const updateTrainingSchedule = () => {
  const id = form.value.id;
  const updatedTrainingSchedule = { ...form.value };

  // 判断训练安排是否已完成，如果已完成则不允许更新
  if (updatedTrainingSchedule.status === '已完成') {
    ElMessage.warning('已完成的训练安排不能修改');
    return;
  }

  // 判断是否为自己创建的训练安排，如果不是则不允许更新
  if (updatedTrainingSchedule.coachName !== name.value) {
    ElMessage.warning('只能修改自己创建的训练安排');
    return;
  }

  axios.put(`http://localhost:8080/trainingschedule/update/${id}`, updatedTrainingSchedule)
      .then(response => {
        ElMessage.success('修改训练安排成功');
        getData(); // 更新表格显示
      })
      .catch(error => {
        ElMessage.error('修改训练安排失败');
        console.error(error);
      });
};

const handleComplete = (row) => {
  if (row.status === '已完成') {
    ElMessage.info('此训练安排已完成，无需再完成');
    return;
  }
  if (row.coachName !== name.value) {
    ElMessage.error('只有教练本人才能标记训练安排为已完成');
    return;
  }
  ElMessageBox.confirm(
      '您确定要将此训练安排标记为已完成吗?',
      '确认操作',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      } as ElMessageBoxOptions
  ).then(() => {
    axios.put(`http://localhost:8080/trainingschedule/update/${row.id}`, {
      ...row,
      status: '已完成'
    }).then(response => {
      ElMessage.success('训练安排已完成');
      getData();
    }).catch(error => {
      ElMessage.error('设置完成状态失败');
      console.error(error);
    });
  }).catch(() => {
    ElMessage.info('已取消操作');
  });
};

</script>

<style scoped>
.topLocation {
  font-size: 16px;
  font-weight: bold;
  color: #000; /* 文字颜色为黑色 */
  padding: 10px;
  border-bottom: 2px solid #000; /* 底部边框，黑色 */
  display: flex;
  align-items: center; /* 垂直居中对齐 */
  justify-content: flex-start; /* 左对齐 */
  margin-bottom: 20px; /* 增加距离 */
}

.topTool {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.el-pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.group {
  white-space: nowrap; /* 防止文字换行 */
  font-size: 14px; /* 设置字体大小为 14px */
}
</style>
